
package com.hanxiaozhang.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Logger;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.net.URISyntaxException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 功能描述: <br>
 * 〈Yaml工具类〉
 *
 * @Author:hanxinghua
 * @Date: 2022/4/25
 * @since 1.0.0
 */
@Slf4j
public class YamlUtil {

    /**
     * 文件解析
     *
     * @param file
     * @param nodes
     * @return
     */
    public static Map parse(File file, String nodes) {
        Yaml yaml = new Yaml();
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            log.error("yaml parse error is [{}]", e);
            throw new RuntimeException(e.getMessage());
        }
        Map<String, LinkedHashMap> map = (LinkedHashMap) yaml.load(inputStream);
        return parse(map, nodes.split("\\."));
    }

    /**
     * 流解析
     *
     * @param inputStream
     * @param nodes
     * @return
     */
    public static Map parse(InputStream inputStream, String nodes) {
        Yaml yaml = new Yaml();
        Map<String, LinkedHashMap> map = (LinkedHashMap) yaml.load(inputStream);
        return parse(map, nodes.split("\\."));
    }

    /**
     * 流解析到实体
     * Tips：实体必须是完整的实体，属性也不能少
     * 我还没有测试通 todo
     *
     *
     * @param inputStream
     * @param type
     * @param <T>
     * @return
     */
    @Deprecated
    public static <T> T parse(InputStream inputStream, Class<T> type) {
        Yaml yaml = new Yaml();
        return yaml.loadAs(inputStream, type);
    }


    /**
     * 深拷贝复制
     *
     * @param map
     * @param nodes
     * @return
     */
    private static Map parse(Map<String, LinkedHashMap> map, String[] nodes) {
        Map nm = map.get(nodes[0]);
        if (nodes.length == 1) {
            return nm;
        }
        String[] ns = new String[nodes.length - 1];
        System.arraycopy(nodes, 1, ns, 0, ns.length);
        return parse(nm, ns);
    }


}
